/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-07-31     Administrator       the first version
 */

#include <rtthread.h>
#include "hal_data.h"
#include <rtdevice.h>
#include "sensor_renesas_isl29035.h"
#include "lcd1602.h"

#define PKG_USING_ISL29035_I2C_BUS_NAME "i2c1"

struct rt_sensor_data sensor_data;
rt_thread_t isl29035_thread;

static void isl29035_light_read_entry(void *parameter);
static int isl29035_thread_start(void);


int rt_hw_isl29035_port(void)
{
    struct rt_sensor_config cfg;
    cfg.intf.dev_name  = PKG_USING_ISL29035_I2C_BUS_NAME;
    rt_hw_isl29035_init("isl29035", &cfg);
    return RT_EOK;
}
INIT_DEVICE_EXPORT(rt_hw_isl29035_port);

static int isl29035_thread_start(void)
{
    isl29035_thread = rt_thread_create("isl29035",
                                      isl29035_light_read_entry,
                                      "li_isl29035",
                                      1024,
                                      5,
                                      20);
    if (isl29035_thread != RT_NULL)
    {
        rt_thread_startup(isl29035_thread);
    }

    return RT_EOK;
}
INIT_APP_EXPORT(isl29035_thread_start);

static void isl29035_light_read_entry(void *parameter)
{
    rt_tick_t start_tick = rt_tick_get();
    rt_device_t dev = RT_NULL;
    rt_size_t res;

    dev = rt_device_find(parameter);
    if (dev == RT_NULL)
    {
        rt_kprintf("Can't find device:%s\n", parameter);
        return;
    }

    if (rt_device_open(dev, RT_DEVICE_FLAG_RDWR) != RT_EOK)
    {
        rt_kprintf("open device failed!\n");
        return;
    }
    rt_device_control(dev, RT_SENSOR_CTRL_SET_ODR, (void *)100);

    while (1)
    {
        res = rt_device_read(dev, 0, &sensor_data, 1);
        if (res != 1)
        {
            rt_kprintf("read data failed!size is %d\n", res);
            rt_device_close(dev);
            return;
        }
        else
        {
            rt_kprintf("lux:%ld, timestamp:%5d\n",
                        sensor_data.data.light,
                        sensor_data.timestamp);
        }

        rt_thread_delay_until(&start_tick, 200);
    }
}
